package hu.debrecen.adastra.card.service;

import hu.debrecen.adastra.card.repository.domain.Account;
import hu.debrecen.adastra.card.service.achievement.AchievementService;
import hu.debrecen.adastra.card.service.domain.Card;
import hu.debrecen.adastra.card.service.impl.DummyBotPlayMode;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;

import com.google.common.collect.Iterables;

public class HeartbeatService {

	private static final Logger LOGGER = LoggerFactory.getLogger(HeartbeatService.class);

	private final BotService botService;

	private final GameStoreService gameStoreService;

	private final AchievementService achievementService;

	public HeartbeatService(final BotService botService, final GameStoreService gameStoreService, final AchievementService achievementService) {
		super();
		this.botService = botService;
		this.gameStoreService = gameStoreService;
		this.achievementService = achievementService;
	}

	@Scheduled(fixedRate = 1000 * 5)
	void beat() {
		HeartbeatService.LOGGER.trace("heartbeat");

		this.botService.call();

		this.cleanUp();
	}

	void cleanUp() {

		for (AbstractGame<?> game : Iterables.concat(this.gameStoreService.getFinishedGames(), this.gameStoreService.getRunningGames())) {
			this.achievementService.evaluate(game);
		}

		for (AbstractGame<?> game : this.gameStoreService.getOrphanaGames()) {
			HeartbeatService.LOGGER.debug("Game({}) has been removed.", game.getGameId());
			this.gameStoreService.removeGame(game);
		}

		for (AbstractGame<?> game : this.gameStoreService.getExpiredByLastActionGames()) {

			Account account = game.getLastRound().getActualPlayer();
			HeartbeatService.LOGGER.trace("Bot calls instead of Player({}) in Game({})", account, game.getGameId());
			Card card = new DummyBotPlayMode().evaluate(game.getLastState(account));
			HeartbeatService.LOGGER.trace("Bot calls card({})", card);
			game.call(account, card.getType(), card.getSuit());

		}

	}

}
